@file:Suppress("unused")

package com.rzico.sbl.other

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.xinnuo.common.helper.dp2px

class SpaceIndexDecoration
@JvmOverloads
constructor(
    private val top: Float = 13f,
    private val bottom: Float = 13f,
    private val index: Int = 0,
    private val hasLast: Boolean = true
) : RecyclerView.ItemDecoration() {

    /**
     * 设置ItemView的内嵌偏移长度（inset）
     *
     * @param outRect 全为0的rect，用来指定偏移区域
     * @param view    指RecyclerView中的Item
     * @param parent  指RecyclerView本身
     * @param state   状态
     */
    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        val position = parent.getChildLayoutPosition(view)

        if (parent.layoutManager is LinearLayoutManager) {
            val manager = parent.layoutManager as LinearLayoutManager
            val itemCount = manager.itemCount

            when {
                position < index -> outRect.set(0, 0, 0, 0)
                position + 1 == itemCount -> outRect.set(
                    0,
                    dp2px(top),
                    0,
                    if (hasLast) dp2px(bottom) else 0
                )
                else -> outRect.set(0, dp2px(top), 0, 0)
            }
        }
    }

}
